package org.csu.mypetstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.mypetstore.commonResponse.CommonResponse;
import org.csu.mypetstore.domin.Item;
import org.csu.mypetstore.domin.Order;
import org.csu.mypetstore.persistence.OrderMapper;
import org.csu.mypetstore.service.ItemService;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("OrderService")

public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ItemService itemService;

    @Override
    public CommonResponse<Order> addOrder(Order order) {
        int x=orderMapper.insert(order);
        if(x==0||order.getItemid()==null){
            return CommonResponse.createForError("新增订单失败");
        }
        CommonResponse<Item> commonResponse=itemService.getItem(order.getItemid());
        int num=order.getNum();
        Item item=commonResponse.getData();
        item.setClick(item.getClick()+num);
        itemService.updateItem(item);
        return CommonResponse.createForSuccess("新增订单成功",order);
    }

    @Override
    public CommonResponse<List<Order>> getOrderListByUsername(String username) {
        QueryWrapper<Order> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        List<Order> orderList=orderMapper.selectList(queryWrapper);
        if(orderList==null){
            return CommonResponse.createForError("获取订单失败");
        }
        return CommonResponse.createForSuccess("获取订单成功",orderList);
    }

    @Override
    public CommonResponse<String> deleteOrderById(int id) {
        QueryWrapper<Order> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",id);
        int x=orderMapper.delete(queryWrapper);
        if(x==0){
            return CommonResponse.createForError("删除订单失败");
        }
        return CommonResponse.createForSuccess("删除订单成功");
    }
}
